package com.jiaolong.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiaolong.converter.OrderConverter;
import com.jiaolong.domain.OrderDo;
import com.jiaolong.dto.OrderDto;
import com.jiaolong.mapper.OrderMapper;
import com.jiaolong.utils.CreMchOrderNoUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class OrderService extends ServiceImpl<OrderMapper, OrderDo> implements IService<OrderDo> {

    @Resource
    OrderMapper orderMapper;

    /**
     * 新增订单
     * @param orderDto
     */
    public String saveOrder(OrderDto orderDto) {
        OrderDo orderDo = OrderConverter.INSTANCE.dto2Do(orderDto);
        // 生成订单号
        String mchOrderNo = CreMchOrderNoUtil.getOnlyNo().toString();
        orderDo.setMchOrderNo(mchOrderNo);
        // 默认支付未成功，设为0
        orderDo.setComplete(0);
        Date nowTime = new Date();
        orderDo.setCreateTime(nowTime);
        orderDo.setUpdateTime(nowTime);
        this.save(orderDo);
        return mchOrderNo;
    }

    /**
     * 根据订单号查询订单
     * @param mchOrderNo
     * @return
     */
    public OrderDo getOrderByMchOrderNo(Long mchOrderNo) {
        LambdaQueryWrapper<OrderDo> wrapper = new LambdaQueryWrapper<OrderDo>()
                .eq(OrderDo::getMchOrderNo, mchOrderNo.toString());
        return orderMapper.selectOne(wrapper);
    }

    /**
     * 根据订单号修改订单状态
     * @param outTradeNo
     */
    public void updateOrderStatus(String outTradeNo) {
        LambdaUpdateWrapper<OrderDo> wrapper = new LambdaUpdateWrapper<OrderDo>()
                .eq(OrderDo::getMchOrderNo, outTradeNo)
                        .set(OrderDo::getComplete, "1");
        orderMapper.update(wrapper);
    }
}
